<template>
  <div>
    <slot name="paper" :content="content">
    </slot>
  </div>
</template>

<script>
import { reactive, toRefs, onMounted, ref, watch, onUnmounted } from 'vue'
export default {
  name: 'Printer',
  props: {
    //内容
    printerInfo: {
      type: String,
      default: ""
    },
    //速度
    duration: {
      type: Number,
      default: 100
    },
    //延迟
    delay: {
      type: Number,
      default: 3000
    },
    working: {
      type: Boolean,
      default: true
    },
    once: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const data = reactive({
      content: "",
      cursor: 0,
      timeout: null,
      print: true
    })
    const timer = ref()
    watch(() => props.working, (newValue, oldValue) => {
      toBegin();
    }
    )
    watch(() => props.printerInfo, (newValue, oldValue) => {
      toBegin();
    }
    )
    watch(() => data.cursor, (newValue, oldValue) => {
      data.content = props.printerInfo.slice(0, newValue)
    }
    )

    /**
  * 定时
  */
    const start = (work) => {
      //延迟
      data.timeout = setTimeout(() => {
        //速度
        timer.value = setInterval(() => {
          work();
          if (data.cursor === 0 || (data.cursor === props.printerInfo.length && !props.once)) {
            //此处为了延迟
            clearInterval(timer.value);
            start(work);
          } else if (data.cursor === props.printerInfo.length && props.once) {
            clearInterval(timer.value);
          }
        }, props.duration);
      }, props.delay)
    }
    /**
     * 逻辑
     */
    const work = () => {
      let cursor = data.cursor;
      cursor += data.print ? 1 : -1;
      if (data.print) {
        if (cursor === props.printerInfo.length + 1) {
          cursor -= 2;
          data.print = !data.print;
        }
      } else {
        if (cursor === -1) {
          cursor += 2;
          data.print = !data.print;
        }
      }
      data.cursor = cursor;
    }
    const toBegin = () => {
      data.cursor = 0;
      if (data.timeout !== null) {
        clearTimeout(data.timeout);
        if (timer.value !== null) {
          clearInterval(timer.value);
        }
      }
      if (props.working) {
        start(work);
      } else {
        data.content = props.printerInfo;
      }
    }
    onMounted(() => {
      if (props.working) {
        //this.work：引用函数
        //this.work()：执行函数
        start(work);
      } else {
        data.content = props.printerInfo
      }
    })
    //在页面销毁之前先销毁定时器
    onUnmounted(() => {
      clearTimeout(timer.value)
      timer.value = ""
    })
    return {
      ...toRefs(data),
    }
  },
}

</script>
<style scoped lang='scss'></style>